package org.adnet.sdk.ad;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.adnet.sdk.AppManager;
import org.adnet.sdk.HttpUtils;
import org.adnet.sdk.Utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class SelfAdView extends Dialog {

	private Iterator<SelfAd> iteratorAd;

	Handler handler = new Handler();
	
	public SelfAdView(final Context context) {
		super(context);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		setCanceledOnTouchOutside(false);
		RelativeLayout main = new RelativeLayout(context);
		RelativeLayout.LayoutParams mainP = new RelativeLayout.LayoutParams(-1,
				-1);

		main.setLayoutParams(mainP);

		final ImageView ad = new ImageView(context);
		ad.setLayoutParams(mainP);

		main.addView(ad);

		setContentView(main);

		if (iteratorAd == null
				|| Calendar.getInstance().getTimeInMillis()
						- Utils.getLastRequestAdTime(context) >= 3600 * 24) {
			Utils.saveLastRequestAdTime(context, Calendar.getInstance().getTimeInMillis());
			
			new Thread(new Runnable() {
				public void run() {

					List<SelfAd> tmp = HttpUtils.getAd(context);
					if (tmp != null && tmp.size() > 0) {
						iteratorAd = tmp.iterator();
						
						handler.post(new Runnable() {
							
							@Override
							public void run() {
								SelfAd tmp = null;
								while (iteratorAd.hasNext()) {
									SelfAd i = iteratorAd.next();
									if (!AppManager.isAppInstalled(context, i.getPackagename())) {
										tmp = i;
										break;
									}
								}
								
								if (tmp == null) {
									Log.d("mysdk", "no available ad");
									return;
								}
								Utils.saveLastAdTime(context, Calendar.getInstance().getTimeInMillis());
								final SelfAd selfAd = tmp;
								ad.setImageDrawable(Drawable.createFromPath(selfAd.getLocalimg()));
								
								ad.setOnClickListener(new View.OnClickListener() {
									
									@Override
									public void onClick(View v) {
										
										try {
											String url = selfAd.getDownloadUrl();
											Intent i = new Intent(Intent.ACTION_VIEW);
											i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
											i.setData(Uri.parse(url));
											context.startActivity(i);
											dismiss();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
								
								show();
							}
						});
					}
				}
			}).start();
		}
	}
}
